package com.wzdigit.wms.raw.service.mid;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.mes.basic.api.BasicDataItemDetailApi;
import com.wzdigit.mes.basic.api.BasicVendorApi;
import com.wzdigit.mes.basic.dto.DataItemDetailDTO;
import com.wzdigit.mes.basic.dto.VendorDTO;
import com.wzdigit.wms.basic.client.response.basic.SkuBaseResponse;
import com.wzdigit.wms.basic.domain.asn.AsnDtl;
import com.wzdigit.wms.basic.domain.asn.AsnHeader;
import com.wzdigit.wms.basic.domain.mapping.CodeMapping;
import com.wzdigit.wms.basic.domain.mid.JobSyncErrorData;
import com.wzdigit.wms.basic.domain.transfer.GdnDtl;
import com.wzdigit.wms.basic.domain.transfer.GdnHeader;
import com.wzdigit.wms.basic.enums.*;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.mid.JobSyncErrorDataMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnHeaderMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.GdnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.GdnHeaderMapper;
import com.wzdigit.wms.basic.service.code.CodeMappingService;
import com.wzdigit.wms.raw.constant.SyncTypeConstant;
import com.wzdigit.wms.raw.domain.dto.IfVmiasnHeaderDto;
import com.wzdigit.wms.raw.domain.mid.IfVmiasnDtl;
import com.wzdigit.wms.raw.domain.mid.IfVmiasnHeader;
import com.wzdigit.wms.raw.exception.SyncException;
import com.wzdigit.wms.raw.mapper.mid.IfVmiasnDtlMapper;
import com.wzdigit.wms.raw.mapper.mid.IfVmiasnHeaderMapper;
import net.dreamlu.mica.core.utils.BeanUtil;
import net.dreamlu.mica.core.utils.CollectionUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 接口中间表-采购订单 同步 采购订单
 * </p>
 *
 * @author chao shuai
 * @since 2021-06-10
 */
@Service
public class IfVmiasnHeaderService {

    @Autowired
    private IfVmiasnHeaderMapper ifVmiasnHeaderMapper;

    @Autowired
    private IfVmiasnDtlMapper ifVmiasnDtlMapper;

    @Autowired
    private GdnHeaderMapper gdnHeaderMapper;

    @Autowired
    private GdnDtlMapper gdnDtlMapper;

    @Autowired
    private AsnHeaderMapper asnHeaderMapper;

    @Autowired
    private AsnDtlMapper asnDtlMapper;

    @Autowired
    private JobSyncErrorDataMapper jobSyncErrorDataMapper;

    @Reference(version = "${dubbo.consumers.basic.vendor.api:1.0.0}", check = false, timeout = 300000)
    private BasicVendorApi  basicVendorApi;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SyncErrorDataService syncErrorDataService;

    @Autowired
    CodeMappingService codeMappingService;

    @Reference(version = "${dubbo.consumers.basic.data.item.detail.api:1.0.0}", check = false, timeout = 300000)
    private BasicDataItemDetailApi dataItemDetailApi;


    @Value(value = "${default_owner.code}")
    private String DEFAULT_OWNER;

    @Value(value = "${default_owner.name}")
    private String DEFAULT_OWNER_NAME;


    

    private final String syncType = SyncTypeConstant.IF_VMIASN_TO_GDN_OR_ASN;

    public List<IfVmiasnHeaderDto> selectSyncData() {
        ArrayList<IfVmiasnHeaderDto> ifVmiasnHeaderDtos = new ArrayList<>();
        QueryWrapper<IfVmiasnHeader> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("Attribute10","1").or().isNull("Attribute10");
        List<IfVmiasnHeader> selectSyncData = ifVmiasnHeaderMapper.selectList(queryWrapper);
        if (!CollectionUtil.isEmpty(selectSyncData)) {
            for (IfVmiasnHeader ifVmiasnHeader : selectSyncData) {
                IfVmiasnHeaderDto ifVmiasnHeaderDto = new IfVmiasnHeaderDto();
                BeanUtil.copyNonNull(ifVmiasnHeader, ifVmiasnHeaderDto);
                List<IfVmiasnDtl> ifSalesreturnDtls = ifVmiasnDtlMapper.selectList(new QueryWrapper<>(
                        new IfVmiasnDtl().setIfVmiasnHeaderId(ifVmiasnHeader.getIfVmiasnHeaderId())
                ));
                ifVmiasnHeaderDto.setIfVmiasnDtlList(ifSalesreturnDtls);
                ifVmiasnHeaderDtos.add(ifVmiasnHeaderDto);
            }

        }
        return ifVmiasnHeaderDtos;
    }




    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void syncDataGdn(IfVmiasnHeaderDto data, boolean isSyncError) throws Exception {
        String asnNumber = data.getAsnNumber(); //送货单--》发货单号or收货通知单号
        //查询供应商信息
        VendorDTO vendor = basicVendorApi.getVendorByCode(data.getVendorCode());
        if (vendor == null||vendor.getVendorId()==null) {
            throw new SyncException(syncType, asnNumber, "供应商" + data.getVendorCode() + "不存在");
        }


        List<IfVmiasnDtl> ifVmiasnDtlList = data.getIfVmiasnDtlList();

        GdnHeader gdnHeader = new GdnHeader();
        //同步主表信息
        gdnHeader.setGdnNo(asnNumber);
        gdnHeader.setFactory(data.getFactoryCode());
        gdnHeader.setGdnType(GdnTypeEnum.D13.code);
        gdnHeader.setConsigneeId(vendor.getVendorId().longValue());
        gdnHeader.setConsigneeName(vendor.getVendorName());
        gdnHeader.setPlaceOfDelivery(data.getShipTo());
        gdnHeader.setComments(data.getHeaderRemarks());
        gdnHeader.setCreateUser(data.getCreateUser());
        gdnHeader.setCreateTime(data.getCreateTime());
        //TODO
//        DataItemDetailDTO dataItem = dataItemDetailApi.getDataItemDetailByPCodeAndName(DEFAULT_OWNER, DEFAULT_OWNER_NAME);
        DataItemDetailDTO dataItem = dataItemDetailApi.getDefaultDataItemDetailByCode(DEFAULT_OWNER);

        gdnHeader.setOwner(dataItem == null || dataItem.getItemValue() == null ? 0: Integer.valueOf(dataItem.getItemValue()));


        GdnHeader gdnHeaderRecord = gdnHeaderMapper.selectOne(new QueryWrapper<>(new GdnHeader().setGdnNo(asnNumber)));
        if (gdnHeaderRecord == null) {
            gdnHeader.setStatus(GdnHeaderStatusEnum.CREATE.getCode());//新建状态
            gdnHeaderMapper.insert(gdnHeader);
        } else {
            gdnHeader.setModifyTime(new Date());
            gdnHeader.setModifyUser("system");
            gdnHeader.setGdnHeaderId(gdnHeaderRecord.getGdnHeaderId());
            gdnHeaderMapper.updateById(gdnHeader);
        }
        //同步明细

        Integer asnLineNo = 0;

        for (IfVmiasnDtl ifVmiasnDtl : ifVmiasnDtlList) {
            //查询SKUID
            SkuBaseResponse sku = skuMapper.getSkuByCode(ifVmiasnDtl.getItemCode());
            if(sku==null||sku.getSkuId()==null){
                throw new SyncException(syncType, asnNumber, "物料编码" + ifVmiasnDtl.getItemCode() + "不存在");
            }
            //处理仓库信息
            CodeMapping codeMapping = codeMappingService.selectByMappingCode( ifVmiasnDtl.getReceivingWarehouseCode());
            if(codeMapping==null||codeMapping.getCodeMappingId()==null){
                throw new SyncException(syncType, asnNumber,  "仓库" + ifVmiasnDtl.getReceivingWarehouseCode() + "不存在");
            }
            GdnDtl gdnDtl = new GdnDtl();
            gdnDtl.setGdnHeaderId(gdnHeader.getGdnHeaderId());
            String gdnLineStr = ifVmiasnDtl.getAsnLineNum().toString();
            gdnDtl.setGdnLineNo(Integer.parseInt(gdnLineStr));
            gdnDtl.setSkuId(sku.getSkuId());
            gdnDtl.setUnit(ifVmiasnDtl.getUomCode());
            String whsStr = codeMapping.getCodeMappingId().toString();
            gdnDtl.setWhsId(Integer.parseInt(whsStr));
            gdnDtl.setOrderQty(ifVmiasnDtl.getQuantity());
            gdnDtl.setComments(ifVmiasnDtl.getRemark());
            gdnDtl.setDoNo(ifVmiasnDtl.getOrderNumber()+"");
            gdnDtl.setCreateTime(ifVmiasnDtl.getCreateTime());
            gdnDtl.setCreateUser(ifVmiasnDtl.getCreateUser());


            String asnLineStr = ifVmiasnDtl.getAsnLineNum().toString();
            GdnDtl gdnDtlRecord = gdnDtlMapper.selectOne
                    (new QueryWrapper<>(new GdnDtl().setGdnHeaderId(gdnHeader.getGdnHeaderId()).setGdnLineNo(Integer.parseInt(asnLineStr))));
            if (gdnDtlRecord == null) {
                gdnDtl.setCreateUser("system");
                gdnDtl.setCreateTime(new Date());
                gdnDtl.setStatus(GdnDtlStatusEnum.CREATE.getCode());//新建状态
                //TODO
                gdnDtl.setQaStatus(QaStatusEnum.OK.code);
                try {
                    gdnDtlMapper.insert(gdnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, asnNumber, e.getMessage());
                }
            } else {
                gdnDtl.setModifyUser("system");
                gdnDtl.setModifyTime(new Date());
                gdnDtl.setGdnDtlId(gdnDtlRecord.getGdnDtlId());
                try {
                    gdnDtlMapper.updateById(gdnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, asnNumber, e.getMessage());
                }
            }
            int row = ifVmiasnHeaderMapper.updateFlagById(data.getIfVmiasnHeaderId());
            //检查是否有同步失败的记录，有则更新为成功
            JobSyncErrorData jobSyncErrorData = jobSyncErrorDataMapper.getSyncErrorDataByTypeAndCode(syncType, asnNumber);
            if (jobSyncErrorData != null && 0 == jobSyncErrorData.getIsSuccess()) {
                syncErrorDataService.updateSuccessByCode(syncType, asnNumber);
            }
        }

    }


    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void syncDataAsn(IfVmiasnHeaderDto data, boolean isSyncError) throws Exception {
        String asnNumber = data.getAsnNumber();
        //查询供应商信息
        VendorDTO vendor = basicVendorApi.getVendorByCode(data.getVendorCode());
        if (vendor == null||vendor.getVendorId()==null) {
            throw new SyncException(syncType, asnNumber, "供应商" + data.getVendorCode() + "不存在");
        }

        List<IfVmiasnDtl> ifVmiasnDtlList = data.getIfVmiasnDtlList();
        AsnHeader asnHeader = new AsnHeader();
        //同步主表信息
        asnHeader.setAsnNo(asnNumber);
        asnHeader.setFactory(data.getFactoryCode());
        asnHeader.setAsnType(AsnTypeEnum.R13.code);
        asnHeader.setVendorId(vendor.getVendorId());
        asnHeader.setPlaceOfDelivery(data.getShipTo());
        asnHeader.setComments(data.getHeaderRemarks());
        asnHeader.setCreateUser(data.getCreateUser());
        asnHeader.setCreateTime(data.getCreateTime());
        AsnHeader asnHeaderRecord = asnHeaderMapper.selectOne(new QueryWrapper<>(new AsnHeader().setAsnNo(asnNumber)));
        if (asnHeaderRecord == null) {
            asnHeader.setStatus(AsnHeaderStatusEnum.CREATE.code);  //到货通知单状态
            asnHeader.setReleaseStatus(AsnHeaderStatusEnum.CANCEL.code); //ASN释放状态
            asnHeader.setQcStatus( QaStatusEnum.WAIT.code); //质检状态
            asnHeader.setPriority(0); //优先级
            asnHeaderMapper.insert(asnHeader);
        } else {

            asnHeader.setModifyTime(new Date());
            asnHeader.setModifyUser("system");
            asnHeader.setAsnHeaderId(asnHeaderRecord.getAsnHeaderId());
            asnHeaderMapper.updateById(asnHeader);
        }
        //同步明细
        Integer asnLineNo = 0;
        for (IfVmiasnDtl ifVmiasnDtl : ifVmiasnDtlList) {
            SkuBaseResponse sku = skuMapper.getSkuByCode(ifVmiasnDtl.getItemCode());
            if(sku==null||sku.getSkuId()==null){
                throw new SyncException(syncType, asnNumber, "物料编码" + ifVmiasnDtl.getItemCode() + "不存在");
            }
            //处理仓库信息
            CodeMapping codeMapping = codeMappingService.selectByMappingCode( ifVmiasnDtl.getReceivingWarehouseCode());
            if(codeMapping==null){
                 throw new SyncException(syncType, asnNumber,  "仓库" + ifVmiasnDtl.getReceivingWarehouseCode() + "不存在");
            }
            AsnDtl asnDtl = new AsnDtl();
            asnDtl.setAsnHeaderId(asnHeader.getAsnHeaderId());
            asnDtl.setAsnNo(asnHeader.getAsnNo());
            asnDtl.setAsnLineNo(ifVmiasnDtl.getAsnLineNum()+"");
            asnDtl.setSkuId(sku.getSkuId());
            asnDtl.setSkuDesc(sku.getDescCn());
            asnDtl.setUnit(ifVmiasnDtl.getUomCode());
            String whsStr = codeMapping.getCodeMappingId().toString();
            asnDtl.setWhsId(Integer.parseInt(whsStr));
            asnDtl.setOrderQty(ifVmiasnDtl.getQuantity());
            asnDtl.setOrderQtyEa(ifVmiasnDtl.getQuantity());
            asnDtl.setComments(ifVmiasnDtl.getRemark());
            asnDtl.setDoNo(ifVmiasnDtl.getOrderNumber()+"");
            asnDtl.setCreateTime(ifVmiasnDtl.getCreateTime());
            asnDtl.setCreateUser(ifVmiasnDtl.getCreateUser());
            //TODO




            AsnDtl asnDtlRecord = asnDtlMapper.selectOne(new QueryWrapper<>(new AsnDtl().setAsnHeaderId(asnHeader.getAsnHeaderId()).setAsnLineNo(ifVmiasnDtl.getAsnLineNum()+"")));
            if (asnDtlRecord == null) {
                asnDtl.setCreateUser("system");
                asnDtl.setCreateTime(new Date());
                asnDtl.setStatus(GdnDtlStatusEnum.CREATE.getCode());//新建状态
                asnDtl.setQaStatus(QaStatusEnum.WAIT.code);
                asnDtl.setQcStatus(QcStatusEnum.未创建质检单.getCode());
                try {
                    asnDtlMapper.insert(asnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, asnNumber, e.getMessage());
                }
            } else {
                asnDtl.setModifyUser("system");
                asnDtl.setModifyTime(new Date());
                asnDtl.setAsnDtlId(asnDtlRecord.getAsnDtlId());
                try {
                    asnDtlMapper.updateById(asnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, asnNumber, e.getMessage());
                }
            }
            int row = ifVmiasnHeaderMapper.updateFlagById(data.getIfVmiasnHeaderId());
            //检查是否有同步失败的记录，有则更新为成功
            JobSyncErrorData jobSyncErrorData = jobSyncErrorDataMapper.getSyncErrorDataByTypeAndCode(syncType, asnNumber);
            if (jobSyncErrorData != null && 0 == jobSyncErrorData.getIsSuccess()) {
                syncErrorDataService.updateSuccessByCode(syncType, asnNumber);
            }
        }

    }

}
